/*
 editor.js by martin $ 2010/05/24 04:29:09
*/
var ENABLE_BR, paletteMode = "color", caretSelection, HSV, hsvmap, pv, Maxsize, paletteToolTip, paletteInfo, paletteLast, SmileyPalette, _hex;
var autoSaveEngine = null, autoSaveFlag = savedLocal = 0, _select_ = 0, TP = -95;
var useBasicColor = 1;
var LOCAL_STORAGE = 0;
var PPBLOG_STORAGE_DATA = [];

if(typeof localStorage == "object"){
 LOCAL_STORAGE = 1;
 for(var i = 0; i < localStorage.length; i++){
  if(/PPBLOG_SAVED_/.test(localStorage.key(i))) PPBLOG_STORAGE_DATA.unshift(localStorage[localStorage.key(i)]);
 }
 PPBLOG_STORAGE_DATA = PPBLOG_STORAGE_DATA.slice(0, 4);
}

var Editor = {
 blockFormat : function(tag){
  var _tag = tag;
  if(tag.match(/class=/)) _tag = tag.replace(/(div|blockquote|pre).+$/, "$1");
  Caret.set('\n<'+tag+'>'+Caret.get()+'</'+_tag+'>\n');
 },
 fontSize : function(size){ Caret.set('<span style="font-size: '+size+';">'+Caret.get()+'</span>');},
 websearch : function(r){ Caret.set('['+r+']'+Caret.get()+'[/'+r+']');},
 smiley : function(face){
  ed.focus(); Caret.set(Caret.get()+face);
  SmileyPalette.hide();
 },
 font : function(tag){
  if(tag=='underline'){ 
   Caret.set('<span class="underline">'+Caret.get()+'</span>');
  } else if(tag=='italic'){
   Caret.set('<span style="font-style: italic;">'+Caret.get()+'</span>');
  } else Caret.set('<'+tag+'>'+Caret.get()+'</'+tag+'>');
 },
 align : function(al){ Caret.set('\n<div style="text-align:'+al+';">'+Caret.get()+'</div>\n');},
 list : function(type){ Caret.set('\n<'+type+'>\n<li> </li>\n<li> </li>\n<li> </li>\n<li> </li>\n</'+type+'>\n');},
 dfn : function(){ Caret.set('\n<dl>\n <dt> </dt>\n  <dd> </dd>\n <dt> </dt>\n  <dd> </dd>\n</dl>\n');},
 link : function(){
  var _link = prompt('リンクしたいアドレスを記入して下さい: ', 'http://');
  if(_link){
   if(!_link.match(/[^;\/\?:@&=\+\$,\w\-\.!~%#\(\)\|]/)){
    if(Caret.get()!=' '){
     Caret.set('<a href="'+_link+'">'+Caret.get()+'</a>');
    } else {
     var site = prompt("サイト名をどうぞ ", "");
     if(site) Caret.set('<a href="'+_link+'" target="_blank">'+site+'</a>');
    }
   } else _link = prompt('URLに不適な文字が入っているような...', _link);
  } else return;
 },
 inserttable : function(){
  var size = prompt('テーブルの行と列の数を*ではさんで指定して下さい（例　2*3）: ', '2*3');
  if(size){
   size = size.split('*');
   var table = '[style].article-content table { border: solid 1px gray; border-collapse: collapse;}\n'
             + '.article-content table td { border: solid 1px gray; padding: 2px; }[/style]\n\n<table style="border: solid 1px gray;">\n';
   for (i=0;i<size[0];i++){
    table += ' <tr>\n';
    for (j=0;j<size[1];j++) table += '  <td> </td>\n';
    table += ' </tr>\n';
   }
   table += '</table>\n';
   ed.focus();
   Caret.set(table);
  }
 },
 setStars : function(){
  var total = prompt('星の数による評価: 何段階で評価しますか？ ', '5');
  if(total){
   if(total>=1) var value = prompt(total+'段階中でどれくらいですか？\n小数は3.5 など.5は指定可です。', '3');
   if(value>=0){
    if(Number(value) > Number(total)){
     alert('最初の数字 '+total+' より小さい数字を指定して下さい。');
     return;
    } else var stars = '[stars:'+value+'/'+total+']';
   }
   ed.focus();
   Caret.set(stars);
  }
 },
 setTime : function(){
  var t = new Date();
  var format = function(v){ return v < 10 ? '0' + v : v;}
  var timenow = t.getFullYear()+'/'+format(t.getMonth()+1)+'/'+format(t.getDate()) + ' '
              + format(t.getHours())+':'+format(t.getMinutes())+':'+format(t.getSeconds());
  Caret.set(timenow);
 },
 insertfile : function(){
  if(typeof sel == UD) Caret.get();
  var w = o('#upfiles');
  w.child(0).src('');
  setTimeout(function(){w.child(0).src(w.$.firstChild.title);}, 10);
  w.sizeTo(530, 410).moveTo(parseInt( (oParts.metrics(0)-530)*.5 ), oParts.metrics(3) + 30).show();
 },
 inserthide : function(){
  var hides = ed.value.match(/<!\-\-HIDE\-\->/g);
  var hidee = ed.value.match(/<!\-\-\/HIDE\-\->/g);
  if(hides){
   if( hidee==null || (hides.length != hidee.length)){
    var s = '開始タグ <!--HIDE--> と 閉じタグ <!--/HIDE-->の数が対応していないようです。\n'
          + '<!--HIDE--> タグの入れ子は出来ません。続けて<!--HIDE-->を挿入するときは、\n'
          + '閉じタグ<!--/HIDE--> を用いて隠す部分を限定して下さい。';
    alert(s); return;
   }
  }
  if(Caret.get()==''){
   Caret.set('<!--HIDE-->');
  } else Caret.set('<!--HIDE-->'+Caret.get()+'<!--/HIDE-->');
 },
 insertAnchor : function(){ Caret.set(Caret.get()+'<!--]]-->');},
 transform : function(){
  if(Caret.get()=='') alert('変換するエリアを選択して下さい。');
  Caret.set(Caret.get().replace(/</g,'&lt;').replace(/>/g,'&gt;'));
 },
 floatclear : function(){ Caret.set(Caret.get()+'<hr class="clear" />');},
 insertmovie : function(){
  if(arguments[1] == 'PCHファイル'){
   var m = ed.value.match(/ppdraw\d{10}\.spch(?:[^:<])/g);
   if(m){
    for (var i = 0, l = m.length; i < l; i++){
     ed.value = ed.value.replace(m[i], '\n[media:'+m[i].replace(/\s/, '')+':300:pch/]\n\n');
    }
   }
  } else {
   var ID, url = prompt(arguments[1] + 'を選択しました。動画へのリンクURLをどうぞ: ', '');
   var a = arguments[0].split(',');
   if(url){
    if(url.indexOf('=') > 0){
     ID = url.replace(/&?feature=related/,'').split(/=/).slice(1).join('=');
     if(url.indexOf('youtube.com') != -1) ID = ID.replace(/.*?v=([^&]+)(?:&.+|)$/, '$1');
    } else {
     ID = url.replace(/\/$/, '').split(/\//).pop();
    }
    if(ID == ''){
     alert('IDが上手く取得できませんでした。直接IDを指定して下さい。');
    }
    if(url.indexOf('ameba.jp') > 0) ID = ID.replace(/:/g, '@');
    Caret.set('['+a[0]+':'+ID+':'+a[1]+':'+a[2]+']');
   }
  }
  ed.focus();
 }
}

function showSmiley(){
 SmileyPalette.moveTo(oParts.evt.pageX + 10, oParts.evt.pageY + 10).toggle();
}

function insertFile(file){ ed.focus();
 if(/\[f/.test(file) || client.MSIE){
  ed.value += file;
 } else Caret.set(Caret.get() + file);
}

function ping_form(target_id, checkbox_id){
 if(!o('#'+target_id).visible() && o('#'+checkbox_id).$.checked==true){
  o('#'+target_id).show();
 } else o('#'+target_id).hide();
}

function amazon(){
 o('#amazon_window').toggle();
 if(o('#amazon_window').visible()) o('#amazon').src('amazon_associate.php'); 
}

function dec2hex(d){ return (d < 16) ? ("0" + Number(d).toString(16)) : Number(d).toString(16);}

var btnsArray = [ // ID, Imagefile, Tip, Function
 'inserttable,table.png,テーブルの挿入,Editor.inserttable()',
 'createlink,link.png,リンクの作成,Editor.link()',
 'insertfile,image.png,画像・添付ファイルの挿入,Editor.insertfile()',
 'bold,bold.png,太字,Editor.font(\'b\')',
 'strong,strong.png,強調,Editor.font(\'strong\')',
 'em,em.png,強勢,Editor.font(\'em\')',
 'italic,italic.png,斜体,Editor.font(\'i\')',
 'underline,underline.png,下線,Editor.font(\'underline\')',
 'del,del.png,取り消し線,Editor.font(\'del\')',
 'color,color.png,文字の色,Palette()',
 'marker,marker.png, マーカー,Palette()',
 'left,left.png,左寄せ,Editor.align(\'left\')',
 'center,center.png,センタリング,Editor.align(\'center\')',
 'right,right.png,右寄せ,Editor.align(\'right\')',
 'list,unorderedlist.png,リスト形式,Editor.list(\'ul\')',
 'olist,orderedlist.png,番号付リスト形式,Editor.list(\'ol\')',
 'dlist,definedlist.png,定義リスト形式,Editor.dfn()',
 'google,google.png,Googleで検索,Editor.websearch(\'g\')',
 'wikipedia,wikipedia.png,Wikipediaで検索,Editor.websearch(\'w\')',
 'continue,continue.png,「続きを読む」タグの挿入,Editor.inserthide()',
 'anchor,anchor.png,ヘッドラインモードでの抜粋指定タグの挿入,Editor.insertAnchor()',
 'transform,transform.png,< や > の変換：&amp;lt; や&amp;gt; に,Editor.transform()',
 'floatclear,hrclear.png,フロートを解除します,Editor.floatclear()',
 'star,star.png,星の数による段階評価,Editor.setStars()',
 'timestamp2,timestamp.png,現在の時刻を入力,Editor.setTime()'
];

var formatArray = [
 ',下から選択',
 'p,段 落',
 'h1,見出し 1',
 'h2,見出し 2',
 'h3,見出し 3',
 'h4,見出し 4',
 'h5,見出し 5',
 'h6,見出し 6',
 'blockquote,引用ブロック',
 'pre,整形ブロック',
 'pre class=&quot;thru&quot;,整形ブロック[class="thru"]',
 'div class=&quot;corner-play&quot;,角丸DIV',
 'blockquote class=&quot;corner-play&quot;,角丸引用',
 'div class=&quot;corner-play square&quot;,角々DIV',
 'blockquote class=&quot;corner-play square&quot;,角々引用',
 'div class=&quot;corner-play outset&quot;,3D DIV',
 'blockquote class=&quot;corner-play outset&quot;,3D 引用'
];

var fontSizeArray = [',選択　','1,8pt','2,10pt','3,12pt','4,14pt','5,16pt','6,24pt','7,36pt'];

var movieArray = [ //yt|gv|nc|wm ...
 ',,,動画サイト選択　',
 ',,,PCHファイル',
 'yt,425,350,YouTube',
 'gv,400,300,Google Video',
 'nc,312,176,ニコニコ動画',
 'wm,339,300,ワッチミー!TV',
 'mm,320,240,mooom',
];

function buildSmileyButton(){
 SmileyPalette = oParts.create('div#smileyPalette', 'z-index: 2100;'); var code = '';
 smileyArray.forEach(function(s, i){
  var f = s.split(',');
  if(i!=0 && i%6==0) code += '<br />';
  code += '<img class="smiley" src="smiley/'+f[0]+'" title="'+f[1]+'" />';
 });
 SmileyPalette.html(code);
}

function _onsubmit(){
 o("#mode").value = (o("#autoposted").value==1) ? "update" : "submit";
 if(o('#timestamp').$.checked){
  var now = Date.parse(new Date());
  var set = Date.parse(new Date(o("#Y").$.value, (Number(o("#m").$.value)-1), o("#d").$.value, o("#H").$.value, o("#i").$.value, o("#s").$.value));
  if(set - now > 30*1000){
   if(confirm('変更された日付が未来日時なのでオンポスト投稿になります')){
    var onpost = d.createElement('INPUT'); onpost.type = 'hidden'; onpost.name = 'ontime'; onpost.value = 1;
    d.forms[1].appendChild(onpost);
   } else return false;
  }
 }
 return checkTags();
}

function writeToolBar(br, comment, ping, movie, helper){
 var toolbar = o('#toolBar');
 var _fixer = '<input type="checkbox" id="fix-toolbar" value="0" onclick="fixToolBar();" /><label for="fix-toolbar" title="ツールバーを固定します"> Fix mode</label>';
 if(!helper) toolbar.css("border-width: 0; height: 0; overflow: hidden;");
 var _btns = '<div class="entry-submit">';
    _btns += '<input type="submit" class="button" title=" この内容で投稿(公開) " value=" 公 開 " onclick=\'return _onsubmit();\' /> &nbsp;&nbsp; ';
    _btns += '<input type="submit" class="button" name="draft" title="記事は公開されません" value="ドラフト" />&nbsp; &nbsp; &nbsp; &nbsp; ';
    _btns += '<input type="button" name="toggle" class="pv-toggle" title="その場で見栄えのチェック" value="ローカルプレビュー" />';
    _btns += '</div>';
 ENABLE_BR = br;
 var code  = '';
 var selectblock = '<br />';
 selectblock += '<div class="tb-block inline"><span>&nbsp;文の整形</span>\n';
 selectblock += ' <select id="format" onchange=\'Editor.blockFormat(this.value);this.selectedIndex=0;\'>\n';
 formatArray.forEach(function(a){
  var f = a.split(',');
  selectblock += ('  <option value="'+f[0]+'">'+f[1]+'</option>\n');
 });
 selectblock += ' </select>\n </div>\n';
 selectblock += '<div class="tb-block inline"><span>&nbsp;文字サイズ</span>\n';
 selectblock += ' <select id="fontsize" onchange="Editor.fontSize(this.value);this.selectedIndex=0;">\n';
 fontSizeArray.forEach(function(a){
  var f = a.split(',');
  selectblock += ('  <option value="'+f[1]+'">'+f[1]+'</option>\n');
 });
 selectblock += ' </select>\n</div>\n';
 selectblock += '<div class="tb-block inline"><img id="smileyButton" src="Images/smiley-button.png" title="絵文字の挿入" /></div>\n';
 btnsArray.forEach(function(a){
  var b = a.split(',');
  code += (' <img id="'+b[0]+'" class="imgbtn" src="button/'+b[1]+'" title="'+b[2]+'" />\n');
 });
 if(movie){
  selectblock += '<div class="tb-block inline"><span>&nbsp;動画リンク貼り付け</span>\n';
  selectblock += ' <select id="movieinsert" onchange="Editor.insertmovie(this.value, this.options[this.selectedIndex].text);this.selectedIndex=0;">\n';
  movieArray.forEach(function(a){
   var f = a.split(',');
   selectblock += ('  <option value="'+f[0]+','+f[1]+','+f[2]+'">'+f[3]+'</option>\n');
  });
  selectblock += ' </select>\n</div>\n';
 }
 code += selectblock + '\n';
 if(mode == 'pages') code += _fixer;
 if(arguments.length > 0 && mode!='pages'){
  code += '<div class="tb-block">　<button type="button" title="オプションです"'
  code += ' onclick="var ex= o(\'#excerpt\');ex.toggle();ex.visible()?ex.$.focus():ed.focus();return false;">記事の概要</button>　\n';
  code += '<button type="button" title="ページを追加します" onclick="addPage();return false;">ページ追加</button>　\n';
  code += '<button type="button" title="追加ページを削除" onclick="removePage();return false;">ページ削除</button>\n';
  code += '<input type="checkbox" name="allow-comment" id="allow-comment" value="1" '+(comment?'checked="checked"':'')+'/><label for="allow-comment" title="この記事に対してコメントを許可">コメント許可</label>　';
  code += '<input type="checkbox" name="allow-ping" id="allow-ping" value="1" '+(ping?'checked="checked"':'')+'/><label for="allow-ping" title="この記事に対してトラックバックを許可">トラックバック許可</label>　';
  code += _fixer + _btns + '</div>\n';
 }
 toolbar.addChild(oParts.fragment(code));
}

function fixToolBar(){
 if(client.IE6){ alert('この機能はIE6には未対応です..'); return;}
 var fixed = (toolbar.css('position') == 'fixed') ? 1 : 0;
 var help = o('.helper').sib(-1), fixer = o('#fix-toolbar'), pv = o('#preViewArea');
 var help_state = oParts.cookie.get('PPBLOG_HELPER_STATE');
 if(fixed){
  toolbar.css('position: static; width: auto; left:0; top:0; border-color: #ddd;');
  fixer.$.checked = false; pv.css('margin-top: 10px');
  if(help_state==1) help.show(); fixer.sib(1).title('ツールバーを固定します');
 } else {
  if(help.visible()) help.hide();
  if(client.IE8){
   var cw = o("#Page1").$.offsetWidth;
   o("#Page1").css("width:" + (cw - 3) + "px");
  }
  toolbar.css('position: fixed; top: '+ TP +'px; left:'+ (toolbar.offset(0) + 10) +'px; padding:10px; border-color: gold; z-index: 1200;');
  fixer.$.checked = true; fixer.sib(1).title('ツールバー固定を解除します');
 }
 oParts.cookie.set('PPBLOG_FIX_MODE', fixed ? 0 : 1);
}

function addPage(){
 var ta = d.createElement('textarea');
 var tab = d.createElement('DIV');
 var taHandler = d.createElement('DIV');
 var i = o('TEXTAREA').size;
 toggleTextArea(i);
 ta.rows = "15"; ta.cols = "60";
 ta.name = "extended[]";
 ta.id = "Page" + i;
 tab.id = "Page" + i + "Tab";
 tab.className = "page-tab";
 tab.innerHTML = '<span class="pagetab"> Page '+i+' </span>';
 ta.style.background = '#fff url(./Images/extended.png) no-repeat top left';
 taHandler.className = 'textareaHandler'; taHandler.innerHTML = '::::::::::';
 taHandler.title = 'マウスドラッグでテキストエリアのサイズを変更できます';
 o('#writing-area').addChild([tab, ta, taHandler]);
 o(taHandler).on('mousedown', Resizable.init);
 ed = ta; ed.onfocus = function(){ed=this;}
 ed.scrollIntoView(); ed.focus();
}

function removePage(){
 var page = o("TEXTAREA").size - 1;
 var del = false;
 if(page > 1){
  if(o('#Page'+page).value() != ''){
   if(confirm('追加ページを削除します。追加分の文章はその前のテキストエリアに移動するのでご安心を。')){
    del = true;
   }
  } else del = true;
  if(del){
   o('#Page'+(page-1)).$.value += "\n\n"+o('#Page'+page).value();
   o('#writing-area').deleteChild([o('#Page'+page).sib(1), o('#Page'+page), o('#Page'+page+'Tab')]);
   ed = o('#Page'+(page-1)).$;
   var rows = ed.value.replace(/\n/gm, '\t').split(/\t/).length + 2;
   ed.style.height = (rows * 19) + 'px'; ed.focus();
  }
 }
}

function ascii2smiley(html){
 for (var i=0, l, l=smilies.length;i<l;i++){
  html = html.replace(smilies[i][0], smilies[i][1]);
 }
 return html;
}
function modify_tags(str){
 var css,i,tag,m,a,w,h,f,p,re,s,stars,ratio,base,pe,ptype,pcap,_div,wrapw;
 m = str.match(/<img src=(.*?)[^>\/]*?\/>/g);
 if(m){
  for(i=0,l=m.length;i<l;i++){
   a = /<img src=(.*?) alt="([\s\S]*?)"([^>\/]*?)\/>/.exec(m[i]);
   p = a[2].split(':');
   ratio = Maxsize / Math.max(p[1], p[2]);
   if(ratio < 1){
    p[1] = Math.floor(ratio * p[1]);
    p[2] = Math.floor(ratio * p[2]);
   }
   if(p[3]==0 && p[4]==0){ p[3] = p[1]; p[4] = p[2]; }
   wrapw = Number(p[3] > 0 ? p[3] : p[1]); wrapw = p[8] ? wrapw + 9 : wrapw;
   pe = /photo\-effect/.test(a[3]) ? 'no' : '';
   ptype = /[01]/.test(parseInt(p[10])) ? parseInt(p[10]) : o('#polaroid-info').html(); ptype = ptype ? 'polaroid' : 'photo';
   ptype = Number(p[7]) && Number(p[8]) ? ptype : 'photo';
   pcap = p[9] == '' ? '<hr class="clear" />' : '<div class="photo-caption" style="width:' + (wrapw - 9) + 'px;">' + p[9];
   _div = ptype == 'polaroid' ? '</div></div></div>' : '</div></div>';
   _div = (ptype=='photo'?'</div>':'') + pcap + _div;
   str = str.replace(m[i], '<div class="'+(pe?'':ptype)+' al-'+p[6]+'" style="width:'+wrapw+'px;"><div class="'+((pe||!Number(p[7]))?'no':'')+'shadow"><img'+(Number(p[8])?' ':' class="borderless" ')+' src='+a[1]+' width="'+p[3]+'" height="'+p[4]+'" alt="'+p[5]+'" '+a[3]+'/>' + _div);
  }
 }
 re = /\[stars:(\d+?(\.5|))\/(\d+?)\]/g;
 m = str.match(re);
 if(m){
  for(i=0,l=m.length;i<l;i++){
   a = re.exec(m[i]);
   w = Number(a[1]); h = Number(a[2]); f = Number(a[3]);
   stars = '<span class="stars">';
   for (j=0;j<Math.floor(w);j++) stars += '<img src="'+ImagePath+'star.png" alt=""/>';
   stars += /\.5/.test(h) ? '<img src="'+ImagePath+'star-half.png" alt=""/>' : '';
   for (j=0;j<Math.floor(f-w);j++) stars += '<img src="'+ImagePath+'star-null.png" alt=""/>';
   stars += '</span>\r\n';
   str = str.replace(m[i], stars);
  }
 }
 str = str.replace(/\|/gm, '&#124;').replace(/`/gm, '&#96;');
 str = str.split('\r\n').join('`'); str = str.split('\n').join('`');
 re = /\[(yt|gv|nc|wm|mm|pv):([^:]+?):(\d+?|):(\d+?|)\]/g;
 m = str.match(re);
 if(m){
  var embeds = {
   'yt' : ['http://www.youtube.com/v/', 'application/x-shockwave-flash', '', '425,350'],
   'gv' : ['http://video.google.com/googleplayer.swf?docId=', 'application/x-shockwave-flash', 'id="VideoPlayback"', '400,300'],
   'nc' : ['http://www.nicovideo.jp/thumb?v=', 'IFRAME', '', '312,176'],
   'wm' : ['http://www.watchme.tv/p/video_output.swf?mid=', 'application/x-shockwave-flash', '', '339,300'],
   'mm' : ['http://mooom.jp/P320x240.swf?m=', 'application/x-shockwave-flash', 'wmode="transparent" quality="high" scale="noscale"', '320,240'],
   'pv' : ['http://peevee.tv/pluginplayerv4.swf?video_id=', 'application/x-shockwave-flash', '', '333,298']
  };
  for(i=0,l=m.length;i<l;i++){
   a = re.exec(m[i]);
   re.lastIndex = 0;
   s = a[1]; tag = a[2]; w = Number(a[3]); h = Number(a[4]);
   for (var j in embeds){
    base = embeds[j][0];
    if(j==s){
     if(embeds[j][1]=='IFRAME'){
      css = ' style="width:'+w+'px; height:'+h+'px;border:solid 1px #ddd;" ';
      if(client.MSIE){
       f = '<iframe width="'+w+'" height="'+h+'" src="'+base+tag+'"'+css+'scrolling="no" frameborder="0"></iframe>';
      } else {
       f = '<object type="text/html" data="'+base+tag+'"'+css+'></object>';
      }
     } else {
       f = '<object style="width:'+w+'px; height:'+h+'px;"><param name="movie" value="'+base+tag+'"></param>'
         + '<embed src="'+(base+tag)+'" type="'+embeds[j][1]+'" '+embeds[j][2]+' width="'+w+'" height="'+h+'"></embed></object>';
     }
    }
   }
   f = '<div class="video-link">'+f+'</div>\n';
   str = str.replace(m[i], f);
  }
 }
 re = /\[media:[^:]+?:(?:\d+?|):(?:\w+?|)\/\]/g;
 var a, m = str.match(re);
 if(m){
  for (i = 0, l = m.length; i < l; i++){
   str = str.replace(m[i], '<div class="media-part" style="width:200px;height:200px;line-height:180px;border:solid 1px #aaa;margin:1em auto;text-align:center;"><p>MEDIA(省略)</p></div>');
  }
 }
 var externalLink = ' <img src="'+ImagePath+'external-link.png" width="12" height="12" alt="Link" title="外部リンク" />';
 str = str.replace(/<a href="([^"]+?)"(.*?)>(.+?)<\/a>/g, '<a href="$1" title="新しいウィンドウで開きます" onclick="window.open(this.href,\'\');return false;" rel="nofollow" $2>$3</a>'+externalLink);
 str = str.replace(/[^"\|>]http:\/\/([;\/\?:@&=\+\$,\w\-\.!~%#]+)/gm,
   function (s0, s1){
    return '<a href="http://'+s1+'" title="新しいウィンドウで開きます" onclick="window.open(this.href,\'\');return false;" rel="nofollow">http://'+s1+'</a>'+externalLink;
 });
 str = str.replace(/\[g\](.*?)\[\/g\]/ig,
       '<a href="#weblog" onclick="googleIt(\'$1\');return false;">$1</a><span class="google-it">G</span>');
 str = str.replace(/\[w\](.*?)\[\/w\]/ig,
       '<a href="#weblog" title="Wikipediaで検索" onclick="wikipediaIt(\'$1\');return false;">$1</a><span class="google-it">W</span>');
 str = str.replace(/\[\[|\]\]/g,'');
 m = str.match(/\[file:([^:]+?):([^\/]*?)\/\]/g);
 if(m){
  str += '\n<div class="attached">\n添付ファイル：\n';
  for(i = 0, l = m.length; i < l; i++){
   str = str.replace(m[i], '');
   f = '<img class="attached-icon" src="'+ImagePath+'attached.png" title="ファイルサイズ:'+m[i].split(':')[2].replace('/]', '')+' KB" />&nbsp;';
   str += m[i].split(':')[1].replace(/\d+d?_/, '') + f;
  }
  str += '</div>\n';
 }
 if(o('#_tags') && o('#_tags').value()){
  var tags = o('#_tags').value().split(/[ |　]/), TAG='';
  TAG = '<hr class="clear" /><p class="techrat-entry" title="テクノラティでタグ検索">\n';
  for (var i=0, l=tags.length; i<l; i++){
   TAG += '<a href="http://technorati.com/tag/'+encodeURIComponent(tags[i])+'" rel="tag" onclick="window.open(this.href,\'\');return false;">'+tags[i]+'</a> ';
  }
  TAG += '</p>\n';
  str += TAG;
 }
 return str;
}

function preViewAreaOn(){
 var _html = ed.value, style = _html.match(/\[style\]([^\[]+?)\[\/style\]/i), jscript = _html.match(/\[script\]([^\[]+?)\[\/script\]/i);
 ARTICLE_BOX = ARTICLE_BOX.replace(/<a href="admin.php\?mode=edit.+?<\/a>/, '').replace(/ href="[^"]+?"/g, ' href="#" onclick="return false;"');
 if(style){
  var wrap = d.createElement('div');
  wrap.innerHTML='&nbsp;<style type="text\/css">'+style[1]+'<\/style>';
  d.getElementsByTagName('head')[0].appendChild(wrap.lastChild);
  _html = _html.replace(style[0], '');
 }
 if(jscript){
  var wrap = d.createElement('div');
  wrap.innerHTML='&nbsp;<script type="text\/javascript">'+jscript[1]+'<\/style>';
  d.getElementsByTagName('head')[0].appendChild(wrap.lastChild);
  _html = _html.replace(jscript[0], '');
 }
 _html = modify_tags(_html);
 var _title = !o('#_title').value() ? 'タイトルなし' : o('#_title').value();
 var cat = o('#category').$.value.replace(',', ' &raquo; ');
 var author = o('#author').$.value;
 var id = o("#UID").value();
 _html = my_parser(_html);
 _html = _html.replace(/<!\-\-HIDE\-\->/, '<div class="readmore-div"><span class="readmore" title="もっと読む" onclick=\'readMore(this);return false;\'>もっと読む&raquo;</span><div style="display:none">');
 _html = _html.replace(/(<!\-\-\/HIDE\-\->|<!\-\-END\-\->)/, '</div>\n</div><!--#readmore-div-->');
 var s = ARTICLE_BOX.replace(/%COM%/, ascii2smiley(_html)).replace(/%TITLE%/, _title).replace(/%CAT%/, cat).replace(/%AUTHOR%/, author).replace(/%SBM%/, '');
 pv.css('width:95%').show().html(s);
 for(var i=0, n = pv.$.childNodes, l=n.length; i < l; i++){
  if(n[i].nodeType===1){
   n[i].style.margin = "auto"; break;
  }
 }
 var pres = pv.$.getElementsByTagName('PRE');
 if(pres.length){
  for (var i = 0, PRE; PRE = pres[i++];) PRE.style.height = 'auto';
 }
 toolbar.oriY = toolbar.css('top'); toolbar.css('top: '+TP+'px;');
 cornerPlay(pv.$);
 if(typeof pettieSyntax != UD) pettieSyntax(o('#preViewArea').$);
 if(typeof photoEffect != UD) photoEffect.init();
 o('input.pv-toggle').item(1).view(true);
 if(o('#Page2Tab')){
  var previewHelper = o('#preview-helper');
  if(!previewHelper){
   previewHelper = oParts.create('div#preview-helper', 'font-size: 10pt; font-weight: bold; color: crimson; position: absolute; right: 50px;')
                         .moveTo(null, oParts.metrics(3) + 60)
                         .html('Preview: page ' + ed.id.slice(4));
  } else previewHelper.html('Preview: page ' + ed.id.slice(4));
 }
}

function togglePreViewArea(forced){
 var helper= o('#preview-helper');
 if(forced){
  o('input.pv-toggle').title('その場で見栄えのチェック').value('ローカルプレビュー');
  preViewAreaOff(); if(helper) helper.hide(); return;
 }
 if(!pv.visible()){
  o('input.pv-toggle').title(' プレビュー画面を閉じます ').value('プレビューを閉じる');
  preViewAreaOn(); if(helper) helper.show();
 } else {
  o('input.pv-toggle').title('その場で見栄えのチェック').value('ローカルプレビュー');
  preViewAreaOff(); if(helper) helper.hide();
 }
}
function preViewAreaOff(){
 if(toolbar.oriY){
  toolbar.css('top: ' + toolbar.oriY);
 }
 pv.hide(); ed.focus();
}
function _checked(){ if(!o('#timestamp').$.checked) o('#timestamp').$.checked = true;}
function my_parser(string){
 string = string.replace(/\n/igm, '`');
 var block = '(div|pre|ol|ul|dl|li|dt|dd|form|blockquote|fieldset|table|tr|td|p|center|object|hr|h1|h2|h3|h4|h5|h6|!)';
 if(!ENABLE_BR){
  string = (string[0]=='<'?'':'``')+(string+"``").replace(new RegExp("<"+block+"([^>]*?)>(.+?)<\/"+block+">", "ig"),
   function(){var a = arguments; return '\n<'+a[1]+a[2]+'>'+a[3].replace(/`/g, '\n')+'</'+a[4]+'>\n'});
  string = string.replace(new RegExp("``(.+?)``", "ig"), function(){return "\n<p>"+arguments[1]+"</p>\n";});
  string = string.replace(new RegExp("``(.+?)$", "ig"), '\n<p>$1</p>\n');
  return string.replace(/<p>`<\/p>/gm, '').replace(/`/g, '\n');
 } else {
  string = string.replace(/`/gm, '<br />');
  string = string.replace(new RegExp("<"+block+"([^>]*?)><br \/>", "ig"), '<$1$2>');
  return  string.replace(new RegExp("(?:<br \/>|)<\/"+block+"><br \/>", "ig"), '</$1>');
 }
}

function checkTags(){
 var i, m, reg, ret, tagNum, valid, rep = '', page = 1;
 while (o('#Page'+page)){
  ret = o('#Page'+page).value().replace(/\n/g, '').replace(/<(img|br|hr|param|input|embed)[^>]*?\/>/ig, '');
  reg = new RegExp('(<([a-z0-9]+?)[^>]*?>)', "ig");
  reg.exec(ret); tagNum = reg.lastIndex;
  while (tagNum > 0){
   ret = ret.replace(new RegExp('<([a-z0-9]+?)[^>]*?>[^<]*?<\/\\1>', "ig"), "");
   ret = ret.replace(new RegExp('<([a-z0-9]+?)[^>]*?>(.*?)<\/\\1>', "ig"), "$2");
   tagNum--;
  }
  m = ret.match(new RegExp('(<[a-z0-9]+?[^>]*?>|<\/[a-z0-9]+?[^>]*?>)', "ig"));
  if(m){
   rep += '　　　　　　　　　― ページ'+page+' ―\n';
   for(i = 0; i < m.length; i++) rep += ' '+m+'\n';
   m = '上記タグの対応に問題があるようです。確認して下さい。\n< や > を &lt; や &gt; に変換するボタンも付いてますよ。';
   if(confirm(rep+m+'\n 「OK」でこのまま投稿を続行します。')) return true; else return false;
   rep = '';
  }
  page++;
 };
 return true;
}

function buildPalette(){
 if(!useBasicColor){
  hsvmap = oParts.create('img', 'border:1px solid #aaa; z-index:2100;').dimension(0, 0, 192, 100).src(HSV);
 } else {
  var cols = '', bcolors = ['red','blue','yellow','black','green','silver','lime','gray','olive','white','maroon','navy','purple','teal','fuchsia','aqua'];
  hsvmap = oParts.create('div', 'border:1px solid #aaa; z-index:2100; background: #aaa').dimension(0, 0, 80, 80);
  cols += '<table style="background: #ccc;">';
  cols += '<tr style="margin: auto;">';
 for (i = 1, l = bcolors.length; i<=l; i++){
  cols += '<td id="'+bcolors[i-1]+'" style="padding: 2px; background:'+bcolors[i-1]+'; display: inline-block; width: 14px; height: 14px; font-size: 0;border: solid 1px #aaa;">.</td>';
  if(i%4 == 0) cols += '</tr>\n<tr>';
 }
  cols += '</tr></table>\n';
  hsvmap.html(cols);
 }
 paletteToolTip = oParts.create('div', 'border:solid 1px #333; font:500 13px arial; background:ivory; padding:2px; z-index:2300;');
 paletteInfo = oParts.create('div', 'border:solid 1px #333; font:500 13px arial; background:ivory; padding:2px; z-index:2200;');
 paletteInfo.sizeTo(95, 95);
 paletteLast = oParts.create('div#palette-last', 'border:solid 1px #333; font:500 13px arial; background:ivory; padding:2px; z-index:2201;');
 paletteLast.css('cursor:pointer').sizeTo(20, 20);
 o([hsvmap, paletteToolTip, paletteInfo, paletteLast]).hide();
}

function togglePalette(){
 var css = (paletteMode=="color") ? "color" : "background", ucolor;
 if(this.id && this.id == 'palette-last') ucolor = oParts.cookie.get('PPBLOG_UCOLOR');
 else ucolor = _hex(); ucolor = ucolor ? ucolor : _hex();
 Caret.set('<span style="'+css+':'+ucolor+';">'+caretSelection+"</span>");
 o([hsvmap, paletteInfo, paletteToolTip, paletteLast]).hide();
 oParts.cookie.set('PPBLOG_UCOLOR', ucolor);
}

function Palette(){
 caretSelection = Caret.get();
 if(client.Gecko) o([MozToolTip, MozToolTipShadow]).hide();
 var ucolor = oParts.cookie.get('PPBLOG_UCOLOR');
 if(ucolor) paletteLast.css('background:' + ucolor);
 hsvmap.moveTo(oParts.evt.pageX + 25, oParts.evt.pageY + 10);
 paletteMode = oParts.evt.target.id;
 paletteToolTip.moveTo(hsvmap.X + 30, hsvmap.Y + 20);
 paletteInfo.moveTo(hsvmap.X + (useBasicColor ? 86 : 200), hsvmap.Y);
 paletteLast.moveTo(hsvmap.X - 25, hsvmap.Y);
 o([hsvmap, paletteInfo, paletteToolTip, paletteLast]).css('opacity:1').show();
}

function getRGB(ob){ // ob is IMG Object (HSV map)
 if(!useBasicColor){
  var r = 0, g = 0, b = 0, rmax = 0, gmax = 0, bmax = 0;
  var scaleX = parseInt(ob.W / 6);
  var scaleY = parseInt(ob.H / 2);
  var pbw = parseInt(ob.css('border-width'));
  var x = oParts.evt.pageX - ob.offset(0) - pbw * 2 - 1;
  var y = oParts.evt.pageY - ob.offset(1) - pbw * 2 - 1;

  if(x < 0) x = 0;
  if(x <= scaleX) {
   rmax = 255;  gmax = (x / scaleX) * 255;  bmax = 0;
  } else if (x <= scaleX * 2) {
   x -= scaleX;  rmax = 255 - (x / scaleX) * 255;  gmax = 255;  bmax = 0;
  } else if (x <= scaleX * 3) {
   x -= scaleX * 2;  rmax = 0;  gmax = 255;  bmax = (x / scaleX) * 255;
  } else if (x <= scaleX * 4) {
   x -= scaleX * 3;  rmax = 0;  gmax = 255 - (x / scaleX) * 255;  bmax = 255;
  } else if (x <= scaleX * 5) {
   x -= scaleX * 4;  rmax = (x / scaleX) * 255;  gmax = 0;  bmax = 255;
  } else {
   x -= scaleX * 5;  rmax = 255;  gmax = 0;  bmax = 255 - (x / scaleX) * 255;
  };
  if(y < 0){
   r = g = b = 255;
  } else if (y <= scaleY){
   r = Math.floor(rmax + ((scaleY-y) / scaleY) * (255 - rmax));
   g = Math.floor(gmax + ((scaleY-y) / scaleY) * (255 - gmax));
   b = Math.floor(bmax + ((scaleY-y) / scaleY) * (255 - bmax));
  } else if (y < scaleY * 2){
   r = Math.floor(rmax * ((scaleY * 2-y) / scaleY));
   g = Math.floor(gmax * ((scaleY * 2-y) / scaleY));
   b = Math.floor(bmax * ((scaleY * 2-y) / scaleY));
  } else r = g = b = 0;
  return [Math.abs(r), Math.abs(g), Math.abs(b)];
 } else {
  return '';
 }
};

function AjaxAutoPost(){
 var posts = [];
 var UID = o('#UID').value();
 posts.push('mode=update');
 if(!o('#autoposted').value()){
  if(o('#mode').value() == 'submit') posts[0] = 'mode=submit';
 }
 if(o('#imgs_list'))  posts.push('imgs_list='+o('#imgs_list').value());
 if(o('#media_list')) posts.push('media_list='+o('#media_list').value());
 if(o('#_title').value()=='') o('#_title').value('タイトルなし');
 posts.push('UID='+UID+'&draft=1&type=autopost');
 posts.push('autoposted='+o('#autoposted').$.value);
 posts.push('category='+o('#category').$.value);
 posts.push('title='+encodeURIComponent(o('#_title').$.value));
 if(o('#pm_title') && o('#pm_title') != '') posts.push('pm_title='+o('#pm_title').$.value);
 posts.push('author='+encodeURIComponent(o('#author').$.value));
 posts.push('allow-comment='+o('#allow-comment').$.value);
 posts.push('allow-ping='+o('#allow-ping').$.value);
 posts.push('excerpt='+encodeURIComponent(o('#excerpt').$.value));
 posts.push('com='+encodeURIComponent(o('#Page1').$.value));
 var page = 2;
 while (o('#Page'+page)){
  posts.push('extended['+(page-2)+']='+encodeURIComponent(o('#Page'+page).$.value));
  page++;
 }
 posts = posts.join('&');
 oParts.server.post("admin.php", posts, function(data){
  if(data.match(/^20/)){
   o('#autoposted').$.value = 1;
   var _UID = UID.replace(/d/, '') + 'd';
   UID = _UID;
   o('#Page1').$.value = o('#Page1').value().replace(new RegExp(UID, 'gm'), _UID);
   while (o('#Page'+page)){
    o('#Page'+page).$.value = o('#Page'+page).value().replace(new RegExp(UID, 'gm'), _UID);
    page++;
   }
   o('#autosave-info').html('ドラフト投稿済み: ' + data);
  } else o('#autosave-info').html('');
  ed.focus();
 });
}

function toggleAutoSave(forced){
 if(forced){
  clearInterval(autoSaveEngine); autoSaveEngine = null;
  o('#autosave-info').html('');
  o('#autoSaveServer').$.checked = false;
  o('#autoSaveServerLabel').title('クリックでオートセーブ再開');
  o('#clock').hide();
  return;
 }
 if(autoSaveFlag){
  autoSaveFlag = 0;
  clearInterval(autoSaveEngine); autoSaveEngine = null;
  o('#autosave-info').html('');
  o('#autoSaveServer').$.checked = false;
  o('#autoSaveServerLabel').html('オートドラフト', -1).title('クリックでオートセーブ再開');
  o('#clock').hide();
 } else {
  o('#autoSaveServerLabel').subst('オートドラフト', '').title('クリックで中止します');
  o('#clock').show(1); // inline-block!
  autoSaveFlag = 1;
  clearInterval(autoSaveEngine); autoSaveEngine = null;
  AjaxAutoPost();
  autoSaveEngine = setInterval(AjaxAutoPost, 60000); // 60sec
 }
}

function AutoSaveLocal(){
 if(!LOCAL_STORAGE){
  alert("お使いのブラウザは対応していません。\nIE8やFirefox, Safariなどの最新版をお使いください。");
  return;
 }
 var key = 'PPBLOG_SAVED_' + PPBLOG_STORAGE_DATA.length, b = o('#saveNow');
 if(b.html() !== '今すぐ保存'){
  var at = new Date().toLocaleString(), data = key + '\t' + o('#_title').$.value + '\t' +  ed.value + '\t' + at;
  PPBLOG_STORAGE_DATA.unshift(data);
  PPBLOG_STORAGE_DATA = PPBLOG_STORAGE_DATA.slice(0, 4);
  localStorage[key] = data;
  b.$.disabled = 1;
  o('#savedInfo').html(at + '保存済み');
  savedLocal = 1;
 } else {
  var data = PPBLOG_STORAGE_DATA[0];
  if(data && ed.value.length){
   var text = data.split(/\t/)[2];
   var at = new Date().toLocaleString();
   if(text != ed.value){
    data = key + '\t' + o('#_title').$.value + '\t' +  ed.value + '\t' + at;
    localStorage[key] = data;
    PPBLOG_STORAGE_DATA[0] = data;
    o('#savedInfo').html(at + '上書き保存済み');
   }
  }
 }
}

function showDataHistory(){
 var size = PPBLOG_STORAGE_DATA.length;
 var table = '<p style="padding: 1em;">最大5件の記事データを閲覧・追記出来ます。現在 <strong id="storagecountInfo">'+size+'</strong> 件のデータがローカルに保存されています。<span style="float:right; cursor: pointer"><img src="Images/button-close.png" alt="close" onclick="o(\'#dataHistory\').away()"/> </span></p><table style="text-align: center; font-size: 90%; width: 97%; margin: 1em auto; border-collapse:collapse;"><col style="border: solid 1px #333; width: 20%; vertical-align:top;"><col style="border: solid 1px #333; width: 80%;"><tr style="background: #e6e6fa;"><th>タイトル/保存日時</th><th>保存された文章</th></tr>';
 if(LOCAL_STORAGE){
  if(!localStorage.length || !size){
   alert('保存されたデータはありません');
   return;
  }
  var cw = oParts.metrics(0), ch = oParts.metrics(1);
  var history = oParts.create('div#dataHistory', 'position: fixed; top: 30px; left: 200px; width:'+(cw - 300)+'px; height: '+(ch - 60)+'px; overflow-y: auto; border: double 10px #ff8c00; background: ivory;');
  for(var i = 0; i < size; i++){
   var data = PPBLOG_STORAGE_DATA[i].split(/\t/);
    table += '<tr style="border: solid 1px #333;"><td style="vertical-align:top; padding: .4em; boder: solid 1px #ddd;">'+data[1]+'<br />'+data[3]+'<br /><a href="#" onclick="addSavedData(\''+data[0]+'\');return false;" title="現在のテキストエリアに追記します"><img style="vertical-align:middle;" src="Images/add2_2.png" alt="Add" />このデータを追加する</a><br /><br /><a href="#" onclick="deleteSavedData(\''+data[0]+'\','+i+');return false;" title="ローカルに保存されたこのデータを削除します"><img style="vertical-align:middle;" src="Images/delete.png" alt="Add" />このデータを削除</a></td><td style="text-align: left; padding: .4em; boder: solid 1px #ddd;">'+data[2]+'</td></tr>\n';
  }
  table += '</table>';
  history.html(table);
 }
}

function addSavedData(key){
 var data = localStorage[key];
 ed.value += '\n\n<!--以下追加されたデータです-->\n' + data.split(/\t/)[2];
 o('#dataHistory').away();
}

function deleteSavedData(key, index){
 var tr = oParts.evt.target.parentNode.parentNode, tl = tr.parentNode, tr_count = 0;
 localStorage.removeItem(key);
 PPBLOG_STORAGE_DATA.splice(index, 1);
 o('#storagecountInfo').html(PPBLOG_STORAGE_DATA.length);
 o(tr).away();
 for(var i = 0; i < tl.childNodes.length; i++){
  if(tl.childNodes[i].nodeName == 'TR') tr_count++;
 }
 if(tr_count === 1){
  alert("保存されたデータはすべて削除されました");
  o('#dataHistory').away();
 }
}

var Resizable = {
 target: null,
 init: function(){
  var tar = oParts.target();
  if(tar.klass('textareaHandler')){
   Resizable.done = false;
   Resizable.target = tar.sib(-1);
   Resizable.target.oH = Resizable.target.css('height');
   Resizable.target.oY = oParts.evt.pageY;
   o(d).on('mousemove', Resizable.work);
   o(d).on('mouseup', Resizable.end);
   oParts.evt.preventDefault();
   d.onselectstart = function(){return false};
  }
 },
 work: function(){
  if(Resizable.target.$.nodeName == 'TEXTAREA'){
   Resizable.target.css('height:' + Math.max(20, oParts.evt.pageY - Resizable.target.oY + Resizable.target.oH) + 'px');
  }
 },
 end: function(){
  o(d).off('mousedown', Resizable.init);
  o(d).off('mousemove', Resizable.work);
  Resizable.done = true;
  d.onselectstart = function(){return true};
 }
};

function resizeTextArea(el){
 if(el.scrollHeight > el.offsetHeight){
  el.style.height = el.scrollHeight + 60 + 'px';
  el.nextSibling.scrollIntoView(true);
 }
}

function toggleTextArea(p){
 if(p){
  o('textarea[id^=Page]').each(function(page, index){
   if(index + 1 == p){
    ed = page; ed.focus(); resizeTextArea(ed);
   } else o(page).css('height: 20px;');
  });
 } else {
  if(!this.min){
   o('textarea[id^=Page]').each(function(page){ o(page).css('height: 20px;');});
   this.min = true;
  } else {
   o('textarea[id^=Page]').each(function(page){ resizeTextArea(page);});
   this.min = false;
  }
 }
 if(pv.visible()) togglePreViewArea();
}

 oParts.imgloader({'HSV':'hsvmap.png', 'loaderAni':'loader.gif'}, 'Images/');

function InitEditor(){
 if(!o('#Page1')) return;
 ajaxTooltip('エディタ', '起動中', loaderAni);
 pv = o('#preViewArea');
 ed = o('#Page1');
 toolbar = o('#toolBar');
 Maxsize = o('#maxsize').value();
 buildPalette();
 buildSmileyButton();
 if(mode=='pages'){
  o('#fix-toolbar').hide(); o('#fix-toolbar').sib(1).hide();
 }
 toolbar.on('mouseover', function(e){
  var tar = oParts.target();
  if(tar.klass() || tar.id){
   if(tar.klass('imgbtn') || tar.id == 'smileyButton') tar.css('border-color:#ddd #909080 #909090 #ccc');
   if(tar.klass('smiley')) tar.css('border:outset 1px #ddd');
  }
 });
 toolbar.on('mousedown', function(e){
   var tar = oParts.target();
   if(tar.klass() || tar.id){
   if(tar.klass('imgbtn') || tar.id == 'smileyButton') tar.css('border-color:#909090 #eee #eee #909090');
   if(tar.klass('smiley')) tar.css('border:inset 1px #ddd');
  }
 });
 toolbar.on('mouseout|mouseup', function(){
  var tar = oParts.target();
  if(tar.klass() || tar.id){
   if(tar.klass('imgbtn') || tar.id == 'smileyButton') tar.css('border-color:#eee');
   if(tar.klass('smiley')) tar.css('border:solid 1px #e7e7e7');
  }
  if(oParts.evt.clientY + 1 >= toolbar.rect(1)){
   if(oParts.cookie.get('PPBLOG_FIX_MODE')==1 && !_select_) toolbar.css('top: '+ TP + 'px');
  }
 });
 toolbar.on('mousemove', function(){
  try {if(oParts.evt.clientY <= 2) toolbar.css('top: 0px');} catch(e){;}
 });

 o(d).on('click', function(){
  var tar = oParts.target(), exp, m; if(!tar) return;
  if(tar.klass('imgbtn')){
   exp = new RegExp('^'+tar.id);
   m = oParts.search(exp, btnsArray);
   if(m) eval(m.split(',')[3]);
   if(client.IE6){
    if(tar.id && (tar.id == 'color' || tar.id == 'marker')) o([o('#fontsize'), o('#movieinsert')]).hide();
   }
  }
  if(tar.klass('smiley')){
   exp = new RegExp('^'+tar.src().split('/').pop());
   m = oParts.search(exp, smileyArray);
   if(m) eval(m.split(',')[2]);
  }
  if(tar.$.nodeName=="SELECT") _select_ = 1;
 });
 o("SELECT").on("blur", function(){_select_ = 0;});
 o([hsvmap, paletteLast]).on('mousemove', _hex = function(){
  var hex = '', c = getRGB(hsvmap);
  if(!useBasicColor){
   hex = "#"+dec2hex(c[0])+dec2hex(c[1])+dec2hex(c[2]);
   hsvmap.css('cursor:crosshair');
  } else {
   try { hex = oParts.evt.target.id || '';} catch(e){ hex = '';}
   hsvmap.css('cursor: pointer');
  }
  if(oParts.evt.target && oParts.evt.target.id && oParts.evt.target.id == 'palette-last'){
   hex = '最後に選んだ色です。クリックで入力。';
  }
  paletteToolTip.moveTo(oParts.evt.pageX + 30, oParts.evt.pageY + 20).html(hex);
  paletteInfo.moveTo(hsvmap.X + (useBasicColor ? 86 : 200), hsvmap.Y).css('background-color:' + hex);
  return hex;
 });
 hsvmap.on('mouseout', function(){
  if(useBasicColor) return;
  if(client.MSIE) oParts.evt.relatedTarget = oParts.evt.toElement;
  if(oParts.evt.relatedTarget && oParts.evt.relatedTarget.id && oParts.evt.relatedTarget.id == 'palette-last') return;
  o([hsvmap, paletteInfo, paletteToolTip, paletteLast]).fade(600);
  if(client.IE6) o([o('#fontsize'), o('#movieinsert')]).show(true);
 });
 o([hsvmap, paletteLast]).on('click', togglePalette);
 ed.on('click', function(){
  o([SmileyPalette, hsvmap, paletteInfo, paletteToolTip, paletteLast]).hide();
  if(client.Gecko && typeof MozToolTip != UD) o([MozToolTip, MozToolTipShadow]).hide();
  if(client.IE6) o([o('#fontsize'), o('#movieinsert')]).show(true);
  if(oParts.cookie.get('PPBLOG_FIX_MODE')==1 && mode != 'pages') toolbar.css('top: '+ TP + 'px');
  togglePreViewArea(true);
 });
 o('#smileyButton').on('click', showSmiley);
 o(window).on('unload', function(){if(autoSaveEngine) clearInterval(autoSaveEngine);});
 if(mode != 'pages'){
  o('.textareaHandler').on('mousedown', Resizable.init);
  o('.textareaHandler').on('dblclick', function(){
   var tar = oParts.target().sib(-1);
   if(tar.css('height') == 20 || (tar.$.offsetHeight < tar.$.scrollHeight)) resizeTextArea(tar.$);
   else tar.css('height: 20px');
  });
 }
 SmileyPalette.on('mouseout', function(){
  try {var e = oParts.evt; if((e.target.nodeName+'|'+e.relatedTarget.nodeName).indexOf('IMG') == -1) SmileyPalette.fade();}catch(e){}
 });
 if(o('#pm_title')){
  o('#pm_title').on('blur', function(){
   var uid = o('#UID').$.value.replace('d', ''), logdate = new Date(uid * 1000), yr = logdate.getFullYear();
   var mn = (logdate.getMonth() + 1 < 10) ? '0' + parseInt(logdate.getMonth() + 1) : parseInt(logdate.getMonth() + 1);
   oParts.server.get('ajax.php?type=log&aim='+yr+''+mn, function(log){
   log = log.replace(/\|/g, '\t');
    var rex = '^.+?,' + o('#pm_title').$.value + '\t', m = new RegExp(rex, 'gm').exec(log);
    if(m){
     m = oParts.search(new RegExp(uid), m);
     if(!m){
      alert(mn.replace(/^0/, '') + '月のログに同じPermaLink用タイトルがあるようです。\n別のタイトルにして下さい。');
      o('#pm_title').focus();
     }
    }
   });
  })
 }
 
 /*ed.on('keyup', function(event){
  if(event.keyCode == 13){
   resizeTextArea(ed);
  }
 });*/
 o('#saveNow').$.disabled = 0;
 ed.on('keyup', function(){
  if(savedLocal) o('#saveNow').html('今すぐ保存').title('ローカルに上書き保存します').$.disabled = 0;
 });
 ed.on('focus', function(){ if(o('#dataHistory')) o('#dataHistory').away(); });
 ed.on('blur', function(){ clearInterval(autoSaveEngine); autoSaveEngine= null;});
 ed = ed.$;

 if(mode != 'pages'){
  var targetPage = /page=(\d+)$/.exec(location.href);
  if(targetPage) toggleTextArea(targetPage[1]); else toggleTextArea(1);
  if(o('#Page2Tab')){
   o('div.entry-submit').html('&nbsp;<input name="toggle2" type="button" title="テキストエリアを一括してトグルします" onclick="toggleTextArea();return false;" value=" Shade " />', 'add');
  }
  o('input.pv-toggle').on('click', function(){togglePreViewArea();});
 }
 if(oParts.cookie.get('PPBLOG_FIX_MODE')==1 && mode != 'pages'){
  toolbar.css('opacity: 0').fade(200, 'IN');
  fixToolBar();
 }
 toolbar.css("border-width: 2px; height: auto;").show();
 (function(){toolTip.hide();}).await(500)();
 if(o('#autoSaveServer')) o('#autoSaveServer').$.checked = false;
}

o(window).on('unload', function(){
 clearTimeout(autoSaveEngine); autoSaveEngine = null;
});

o(d).on('blur', function(){ clearInterval(autoSaveEngine);});